import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:path_provider/path_provider.dart';
import 'package:record/record.dart';
import 'package:image_picker/image_picker.dart';
import 'package:file_picker/file_picker.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'InsightsState.dart';
import 'chat_message.dart';
import '../../core/repository/default_api.dart';
import '../../services/device_sn_manager.dart';
import 'dart:developer' as developer;

/// 洞察页控制器
class InsightsLogic extends GetxController {
  /// 状态实例
  final InsightsState state = InsightsState();

  /// Banner轮播控制器
  final PageController pageController = PageController();

  /// 文本输入控制器
  final TextEditingController textController = TextEditingController();

  /// 音频播放器
  final AudioPlayer audioPlayer = AudioPlayer();

  /// 录音器
  final AudioRecorder audioRecorder = AudioRecorder();

  /// 录音文件路径
  String? _recordingPath;

  /// 录音计时器
  Timer? _recordTimer;

  /// 图片选择器
  final ImagePicker _imagePicker = ImagePicker();

  @override
  void onInit() {
    super.onInit();
    _loadInsights();

    // 监听输入框内容变化
    textController.addListener(_onTextChanged);
  }

  @override
  void onReady() {
    super.onReady();
    // 页面准备完成后的逻辑
  }

  /// 输入框内容变化回调
  void _onTextChanged() {
    final hasContent = textController.text.trim().isNotEmpty;
    developer.log(
        '📝 输入框内容变化: hasContent=$hasContent, text="${textController.text}"',
        name: 'AIChat');
    state.hasText.value = hasContent;
  }

  @override
  void onClose() {
    pageController.dispose();
    textController.dispose();
    audioPlayer.dispose();
    audioRecorder.dispose();
    _recordTimer?.cancel();
    super.onClose();
    // 清理资源
  }

  /// 加载洞察数据
  void _loadInsights() {
    state.isLoading.value = true;
    // 模拟数据加载
    Future.delayed(const Duration(seconds: 1), () {
      state.isLoading.value = false;
      state.insights.assignAll([
        '本周睡眠质量比上周提高了15%',
        '建议在晚上10点前开始准备睡觉',
        '您的运动量达到了本周目标的80%',
        '压力水平比上月降低了10%',
      ]);
    });
  }

  /// 刷新洞察
  void refreshInsights() {
    _loadInsights();
  }

  /// 切换小A管家全屏状态
  void toggleAIFullScreen() {
    state.isAIFullScreen.value = !state.isAIFullScreen.value;
  }

  /// 切换输入模式（语音/文本）
  void toggleInputMode() {
    state.isVoiceMode.value = !state.isVoiceMode.value;
  }

  /// 切换附件菜单显示
  void toggleAttachmentMenu() {
    state.showAttachmentMenu.value = !state.showAttachmentMenu.value;
  }

  /// 开始录音
  Future<void> startRecording() async {
    try {
      // 检查录音权限
      if (await audioRecorder.hasPermission() == false) {
        developer.log('❌ 没有录音权限', name: 'AIChat');
        return;
      }

      state.isRecording.value = true;
      state.recordDuration.value = 0;
      developer.log('🎤 开始录音', name: 'AIChat');

      // 获取临时目录
      final directory = await getTemporaryDirectory();
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      _recordingPath = '${directory.path}/voice_$timestamp.m4a';

      // 开始录音
      await audioRecorder.start(
        const RecordConfig(
          encoder: AudioEncoder.aacLc,
          bitRate: 128000,
          sampleRate: 44100,
        ),
        path: _recordingPath!,
      );

      // 开始计时
      _startRecordTimer();

      developer.log('📁 录音文件路径: $_recordingPath', name: 'AIChat');
    } catch (e) {
      developer.log('❌ 开始录音失败: $e', name: 'AIChat');
      state.isRecording.value = false;
    }
  }

  /// 停止录音
  Future<void> stopRecording() async {
    try {
      state.isRecording.value = false;
      _recordTimer?.cancel();

      final duration = state.recordDuration.value;
      developer.log('🎤 停止录音，时长: ${duration}s', name: 'AIChat');

      if (duration < 1) {
        developer.log('⚠️ 录音时间太短', name: 'AIChat');
        await audioRecorder.stop();
        return;
      }

      // 停止录音
      final path = await audioRecorder.stop();
      developer.log('✅ 录音已保存: $path', name: 'AIChat');

      if (path != null) {
        final voiceFile = File(path);
        if (await voiceFile.exists()) {
          developer.log('📤 准备发送语音消息', name: 'AIChat');
          await sendVoiceMessage(voiceFile, duration: duration);
        } else {
          developer.log('❌ 录音文件不存在', name: 'AIChat');
        }
      } else {
        developer.log('❌ 录音路径为空', name: 'AIChat');
      }
    } catch (e) {
      developer.log('❌ 停止录音失败: $e', name: 'AIChat');
    }
  }

  /// 录音计时器
  void _startRecordTimer() {
    _recordTimer?.cancel();
    _recordTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (state.isRecording.value) {
        state.recordDuration.value++;
      } else {
        timer.cancel();
      }
    });
  }

  /// 播放语音
  Future<void> playVoice(String messageId, String voiceUrl) async {
    try {
      if (state.playingVoiceId.value == messageId) {
        // 如果正在播放这条语音，则停止
        await audioPlayer.stop();
        state.playingVoiceId.value = '';
        developer.log('⏸️ 停止播放语音', name: 'AIChat');
      } else {
        // 停止当前播放
        await audioPlayer.stop();

        // 播放新的语音
        state.playingVoiceId.value = messageId;
        developer.log('▶️ 播放语音: $voiceUrl', name: 'AIChat');

        // 判断是本地文件还是网络URL
        if (voiceUrl.startsWith('http')) {
          await audioPlayer.play(UrlSource(voiceUrl));
        } else {
          await audioPlayer.play(DeviceFileSource(voiceUrl));
        }

        // 监听播放完成
        audioPlayer.onPlayerComplete.listen((event) {
          if (state.playingVoiceId.value == messageId) {
            state.playingVoiceId.value = '';
            developer.log('✅ 语音播放完成', name: 'AIChat');
          }
        });
      }
    } catch (e) {
      developer.log('❌ 播放语音失败: $e', name: 'AIChat');
      state.playingVoiceId.value = '';
    }
  }

  /// 选择拍照
  Future<void> selectCamera() async {
    state.showAttachmentMenu.value = false;

    // 检查是否已有文件附件
    if (state.pendingFile.value != null) {
      Toast.show('一次只能发送一个图片或文件');
      return;
    }

    try {
      developer.log('📷 打开相机', name: 'AIChat');

      final XFile? photo = await _imagePicker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1920,
        maxHeight: 1920,
        imageQuality: 85,
      );

      if (photo != null) {
        developer.log('✅ 拍照成功: ${photo.path}', name: 'AIChat');
        final imageFile = File(photo.path);
        
        // 设置待发送的图片
        state.pendingImage.value = imageFile;
        Toast.show('已添加图片，可输入文字后一起发送');
      } else {
        developer.log('❌ 用户取消拍照', name: 'AIChat');
      }
    } catch (e) {
      developer.log('❌ 拍照失败: $e', name: 'AIChat');
      Toast.show('拍照失败，请重试');
    }
  }

  /// 选择照片
  Future<void> selectPhoto() async {
    state.showAttachmentMenu.value = false;

    // 检查是否已有文件附件
    if (state.pendingFile.value != null) {
      Toast.show('一次只能发送一个图片或文件');
      return;
    }

    try {
      developer.log('🖼️ 打开相册', name: 'AIChat');

      final XFile? image = await _imagePicker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1920,
        maxHeight: 1920,
        imageQuality: 85,
      );

      if (image != null) {
        developer.log('✅ 选择照片成功: ${image.path}', name: 'AIChat');
        final imageFile = File(image.path);
        
        // 设置待发送的图片
        state.pendingImage.value = imageFile;
        Toast.show('已添加图片，可输入文字后一起发送');
      } else {
        developer.log('❌ 用户取消选择照片', name: 'AIChat');
      }
    } catch (e) {
      developer.log('❌ 选择照片失败: $e', name: 'AIChat');
      Toast.show('选择照片失败，请重试');
    }
  }

  /// 选择文件
  Future<void> selectFile() async {
    state.showAttachmentMenu.value = false;

    // 检查是否已有图片附件
    if (state.pendingImage.value != null) {
      Toast.show('一次只能发送一个图片或文件');
      return;
    }

    try {
      developer.log('📁 打开文件选择器', name: 'AIChat');

      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: [
          'pdf',
          'doc',
          'docx',
          'xls',
          'xlsx',
          'txt',
          'zip',
          'rar'
        ],
        allowMultiple: false,
      );

      if (result != null && result.files.single.path != null) {
        final filePath = result.files.single.path!;
        final fileName = result.files.single.name;
        final fileSize = result.files.single.size;

        developer.log('✅ 选择文件成功: $fileName (${_formatFileSize(fileSize)})',
            name: 'AIChat');

        // 检查文件大小（限制为 10MB）
        if (fileSize > 10 * 1024 * 1024) {
          Toast.show('文件大小不能超过 10MB');
          return;
        }

        final file = File(filePath);
        
        // 设置待发送的文件
        state.pendingFile.value = file;
        state.pendingFileName.value = fileName;
        Toast.show('已添加文件，可输入文字后一起发送');
      } else {
        developer.log('❌ 用户取消选择文件', name: 'AIChat');
      }
    } catch (e) {
      developer.log('❌ 选择文件失败: $e', name: 'AIChat');
      Toast.show('选择文件失败，请重试');
    }
  }

  /// 格式化文件大小
  String _formatFileSize(int bytes) {
    if (bytes < 1024) {
      return '$bytes B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(2)} KB';
    } else {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(2)} MB';
    }
  }

  /// 发送文本消息（可能包含图片或文件）
  Future<void> sendTextMessage() async {
    final text = textController.text.trim();
    final hasImage = state.pendingImage.value != null;
    final hasFile = state.pendingFile.value != null;

    // 验证：必须有文本或附件
    if (text.isEmpty && !hasImage && !hasFile) {
      developer.log('❌ 消息内容为空', name: 'AIChat');
      return;
    }

    try {
      state.isSending.value = true;

      // 确定 contentType
      String contentType;
      File? attachmentFile;

      if (hasImage) {
        contentType = '3'; // 图片/文字+图片
        attachmentFile = state.pendingImage.value;
        developer.log('📤 发送图片消息${text.isNotEmpty ? '+文字' : ''}', name: 'AIChat');
      } else if (hasFile) {
        contentType = '4'; // 文件/文字+文件
        attachmentFile = state.pendingFile.value;
        developer.log('📤 发送文件消息${text.isNotEmpty ? '+文字' : ''}：${state.pendingFileName.value}', name: 'AIChat');
      } else {
        contentType = '1'; // 纯文字
        developer.log('📤 发送文本消息: $text', name: 'AIChat');
      }

      // 1. 立即添加用户消息到列表
      final userMessage = ChatMessage.userText(
        text,
        imageUrl: hasImage ? state.pendingImage.value!.path : null,
        fileUrl: hasFile ? state.pendingFile.value!.path : null,
        fileName: hasFile ? state.pendingFileName.value : null,
      );
      state.messages.add(userMessage);

      // 清空输入框和附件状态
      textController.clear();
      state.hasText.value = false;
      state.pendingImage.value = null;
      state.pendingFile.value = null;
      state.pendingFileName.value = '';

      // 2. 添加 AI 思考中消息
      final thinkingMessage = ChatMessage.aiThinking();
      state.messages.add(thinkingMessage);

      // 获取设备信息
      final deviceSnManager = Get.find<DeviceSnManager>();
      final deviceSn = deviceSnManager.getDeviceSn();

      // 3. 发送请求
      final response = await DefaultApi().aiSendPost<Map<String, dynamic>>(
        deviceSn: deviceSn,
        deviceContent: text.isNotEmpty ? text : null,
        chatType: '1', // 1: 设备toApp
        contentType: contentType,
        file: attachmentFile,
        isShowLoading: false,
      );

      // 4. 移除思考中消息
      state.messages.removeWhere((msg) => msg.id == thinkingMessage.id);

      if (response != null && response['code'] == 200) {
        developer.log('✅ 消息发送成功', name: 'AIChat');

        // 5. 添加 AI 回复消息
        final data = response['data'];
        if (data != null && data['aichatContent'] != null) {
          final aiMessage = ChatMessage.aiReply(data['aichatContent']);
          state.messages.add(aiMessage);
        }
      } else {
        developer.log('❌ 消息发送失败: ${response?['msg']}', name: 'AIChat');
        // 添加错误提示消息
        final errorMessage = ChatMessage.aiReply('抱歉，发送失败，请重试');
        state.messages.add(errorMessage);
      }
    } catch (e) {
      developer.log('❌ 发送消息异常: $e', name: 'AIChat');
      // 移除思考中消息
      state.messages.removeWhere((msg) => msg.isThinking);
      // 添加错误提示消息
      final errorMessage = ChatMessage.aiReply('抱歉，发生错误，请重试');
      state.messages.add(errorMessage);
    } finally {
      state.isSending.value = false;
    }
  }

  /// 发送语音消息
  Future<void> sendVoiceMessage(File voiceFile, {int duration = 0}) async {
    try {
      state.isSending.value = true;

      // 1. 立即添加用户语音消息到列表
      final userMessage =
          ChatMessage.userVoice(voiceFile.path, duration: duration);
      state.messages.add(userMessage);
      developer.log('📤 发送语音消息，时长: ${duration}s', name: 'AIChat');

      // 2. 添加 AI 思考中消息
      final thinkingMessage = ChatMessage.aiThinking();
      state.messages.add(thinkingMessage);

      final deviceSnManager = Get.find<DeviceSnManager>();
      final deviceSn = deviceSnManager.getDeviceSn();

      // 3. 发送请求
      final response = await DefaultApi().aiSendPost<Map<String, dynamic>>(
        deviceSn: deviceSn,
        chatType: '1',
        contentType: '2', // 2: 语音
        file: voiceFile,
        isShowLoading: false,
      );

      // 4. 移除思考中消息
      state.messages.removeWhere((msg) => msg.id == thinkingMessage.id);

      if (response != null && response['code'] == 200) {
        developer.log('✅ 语音消息发送成功', name: 'AIChat');

        // 5. 添加 AI 回复消息
        final data = response['data'];
        if (data != null && data['aichatContent'] != null) {
          final aiMessage = ChatMessage.aiReply(data['aichatContent']);
          state.messages.add(aiMessage);
        }
      } else {
        developer.log('❌ 语音消息发送失败: ${response?['msg']}', name: 'AIChat');
        final errorMessage = ChatMessage.aiReply('抱歉，发送失败，请重试');
        state.messages.add(errorMessage);
      }
    } catch (e) {
      developer.log('❌ 发送语音消息异常: $e', name: 'AIChat');
      state.messages.removeWhere((msg) => msg.isThinking);
      final errorMessage = ChatMessage.aiReply('抱歉，发生错误，请重试');
      state.messages.add(errorMessage);
    } finally {
      state.isSending.value = false;
    }
  }

  /// 清除待发送的图片
  void clearPendingImage() {
    state.pendingImage.value = null;
    developer.log('🗑️ 清除待发送图片', name: 'AIChat');
  }

  /// 清除待发送的文件
  void clearPendingFile() {
    state.pendingFile.value = null;
    state.pendingFileName.value = '';
    developer.log('🗑️ 清除待发送文件', name: 'AIChat');
  }

  /// 清除所有待发送的附件
  void clearAllPendingAttachments() {
    clearPendingImage();
    clearPendingFile();
  }
}
